﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Minecraft.WorldMap
{
	/// <summary>
	/// Set of helper methods.
	/// </summary>
	internal static class RegionHelper
	{
		internal static const int sectorSize = 4096;
		internal static const int chunkWidth = 32;
		internal static const int chunkDepth = 32;
	
		internal static DateTime ConvertFromUnixTimestamp(int timestamp)
		{
			DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
			return origin.AddSeconds(timestamp);
		}

		internal static int ConvertToUnixTimestamp(DateTime date)
		{
			DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
			TimeSpan diff = date - origin;
			return (int)Math.Floor(diff.TotalSeconds);
		}

		internal static DateTime?[,] ReadUpdateTimes(System.IO.Stream input)
		{
			DateTime?[,] updated = new DateTime?[RegionHelper.chunkWidth, RegionHelper.chunkDepth];
			using (System.IO.Stream dumper = new NamedBinaryTag.DumpStream(input))
			{
				using (System.IO.BinaryReader reader = new System.IO.BinaryReader(dumper))
				{
					for (int z = 0; z < RegionHelper.chunkDepth; z++)
						for (int x = 0; x < RegionHelper.chunkWidth; x++)
						{
							Int32 value = reader.ReadInt32();
							if (value == 0)
								continue;
							byte[] data = BitConverter.GetBytes(value);
							Array.Reverse(data);
							value = BitConverter.ToInt32(data, 0);
							updated[x, z] = RegionHelper.ConvertFromUnixTimestamp(value);
						}
				}
			}
			return updated;
		}

		internal static SortedList<int, Tuple<int, int, byte>> ReadChunksLocations(System.IO.Stream input)
		{
			SortedList<int, Tuple<int, int, byte>> locations = new SortedList<int, Tuple<int, int, byte>>();
			using (System.IO.Stream dumper = new NamedBinaryTag.DumpStream(input))
			{
				using (System.IO.BinaryReader reader = new System.IO.BinaryReader(dumper))
				{
					for (int z = 0; z < RegionHelper.chunkDepth; z++)
						for (int x = 0; x < RegionHelper.chunkWidth; x++)
						{
							Int32 value = reader.ReadInt32();
							if (value == 0)
								continue;
							byte[] data = BitConverter.GetBytes(value);
							byte size = data[3];
							data[3] = data[2];
							data[2] = data[1];
							data[1] = data[0];
							data[0] = 0;
							Array.Reverse(data);
							value = BitConverter.ToInt32(data, 0);
							locations.Add(value, new Tuple<int, int, byte>(x, z, size));
						}
				}
			}
			return locations;
		}
	}
}
